﻿//     Copyright (c) Microsoft Corporation.  All rights reserved.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Gateway.Console.Models;
using Gateway.Console.Services.Azure;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.WindowsAzure;

namespace Gateway.Console.Services.Azure
{
    public class AzureServiceManagement : IDisposable
    {
        protected ConsoleContext _database;
        private bool _ownDatabase;
        protected AuthenticationResult _accessToken;
        protected string _subscriptionId;

        protected AzureServiceManagement(AuthenticationResult accessToken, string subscriptionId)
        {
            this._database = new ConsoleContext();
            this._ownDatabase = true;
            this._accessToken = accessToken;
            this._subscriptionId = subscriptionId;
        }

        protected AzureServiceManagement(AuthenticationResult accessToken, string subscriptionId, ConsoleContext db)
        {
            this._database = db;
            this._ownDatabase = false;
            this._accessToken = accessToken;
            this._subscriptionId = subscriptionId;
        }

        public SubscriptionCloudCredentials GetAzureCredentials()
        {
            return new TokenCloudCredentials(this._subscriptionId, this._accessToken.AccessToken);
        }

        public void Dispose()
        {
            if (this._ownDatabase && this._database != null)
            {
                this._database.Dispose();
            }
            this._database = null;
        }
    }

    static class ParallelExtensions
    {
        public static void ForEach<T>(this IEnumerable<T> src, Action<T> action)
        {
#if _NO_PARALLEL
            foreach (var item in src)
            {
                action(item);
            }
#else
            src
                .AsParallel()
                .WithDegreeOfParallelism(8)
                .WithExecutionMode(ParallelExecutionMode.ForceParallelism)
                .ForAll(action);
#endif
        }

        public static void ForEach<T>(this IEnumerable<T> src, Func<T, Task> action)
        {
#if _NO_PARALLEL
            foreach (var item in src)
            {
                action(item).Wait();
            }
#else
            src
                .AsParallel()
                .WithDegreeOfParallelism(8)
                .WithExecutionMode(ParallelExecutionMode.ForceParallelism)
                .ForAll(item => action(item));
#endif
        }
    }
}